const config = require("./config.js")
const db = uniCloud.database();
const dbCmd = db.command // 取指令
class User {
	// 通过 code 获取用户的 openId 和 access_token
	async getOpenIdAndAccessToken(code) {
		let {
			body
		} = await uniCloud.httpProxyForEip.get(
			'https://api.weixin.qq.com/sns/oauth2/access_token', {
				appid: config.appid,
				secret: config.app_secret,
				code,
				grant_type: 'authorization_code'
			}
		)
		return body
	}
	async getUserInfo(code) {
		let data = JSON.parse(await this.getOpenIdAndAccessToken(code))
		if (data.openid) {
			let {
				body
			} = await uniCloud.httpProxyForEip.get(
				`https://api.weixin.qq.com/sns/userinfo?access_token=${data.access_token}&openid=${data.openid}&lang=zh_CN`
			)
			let users = await db.collection('wechat-user').where({
				openid: data.openid
			}).get()
			let wxUserReturn;
			body = JSON.parse(body)
			if (users.data.length > 0) {
				wxUserReturn = await db.collection('wechat-user').where({
					openid: data.openid
				}).update({
					openid: body.openid,
					nickname: body.nickname,
					avatar: body.headimgurl,
					access_token: data.access_token,
					refresh_token: data.refresh_token,
					sex: body.sex,
					province: body.province,
					city: body.city
				})
			} else {
				wxUserReturn = await db.collection('wechat-user').add({
					openid: body.openid,
					nickname: body.nickname,
					avatar: body.headimgurl,
					access_token: data.access_token,
					refresh_token: data.refresh_token,
					sex: body.sex,
					province: body.province,
					city: body.city
				})
			}
			return {
				nickname: body.nickname,
				avatar: body.headimgurl
			}

		} else {
			return data
		}
	}

	async login(code) {
		let {
			body
		} = await uniCloud.httpProxyForEip.get(
			'https://api.weixin.qq.com/sns/oauth2/access_token', {
				appid: config.appid,
				secret: config.app_secret,
				code,
				grant_type: 'authorization_code'
			}
		)
		let pBody = JSON.parse(body)
		if (pBody.errcode == 40029) {
			return {
				errCode: 401,
				errMsg: "code失效,请刷新页面"
			}
		}
		try {
			let {
				data
			} = await db.collection('wechat-user').where({
				openid: dbCmd.eq(pBody.openid)
			}).get()

			if (data.length > 0) {
				let userInfo = {
					id:data[0]._id,
					nickname:data[0].nickname,
					avatar:data[0].avatar
				} 
				return {
					errCode: 0,
					data: userInfo,
					errMsg: "ok"
				}
			} else {
				return {
					errCode: 3033,
					data: {},
					errMsg: "没有该用户信息请授权登录"
				}
			}
		} catch (e) {
			return {
				errCode: 500,
				errMsg: "服务器致命错误",
				data:{
					openid:pBody.openid
				},
				error: e.message
			}
		}
	}
}

const userModel = new User()
module.exports = userModel
